package yunwo.cn.yzstation.printer;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import yunwo.cn.yzstation.R;
import yunwo.cn.yzstation.base.MyBaseActivity;
import yunwo.cn.yzstation.bean.SetPaintBean;
import yunwo.cn.yzstation.utils.BluetoothUtil;
import yunwo.cn.yzstation.utils.StringUtil;

/**
 * Created by linchubin on 2017/5/9.
 */

public class NewSetPaintActivity extends MyBaseActivity implements View.OnClickListener {
    public static final int MESSAGE_STATE_CHANGE = 1;
    private static final String TAG = "DeviceListActivity";
    private static final boolean D = true;
    DeviceListAdapter mAdapter;
    // 返回额外的意图
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // 成员字段
    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mUPaireDevicesArrayAdapter;

    private BluetoothDevice btDevice;
    private TextView mPairedTitle;
    private TextView mUPaireTitle;
    private Button bt_bluscan, bt_bluback, bt_bludel;
//    private BluetoothService mBTService = null;
    public Handler mhandler;
//    private MyAdapter myAdapter;
    private String paintName;
    private ListView newDevicesListView;
    private String paintName1;
    private List<BluetoothDevice> mPrinterDevices;
    private Spinner mSpinner;

    private RadioGroup mRadioGroup;
    private RadioButton mXt4131;
    private RadioButton mXt432;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        initView();



        mAdapter = new DeviceListAdapter(this);

        mUPaireTitle = (TextView) findViewById(R.id.title_new_devices);





        // 找到并设置为新发现的设备的列表
        newDevicesListView = (ListView) findViewById(R.id.new_devices);

        newDevicesListView.setAdapter(mAdapter);
//        newDevicesListView.setAdapter(myAdapter);
        newDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });


    }

    private String addressSha1;
    private String address1;
    private String addressSha;
    private ImageView linePaintIV;
    private TextView paintNameTV;
    private TextView lineTypeTV;
    private SharedPreferences addressShare;
    private SharedPreferences.Editor addresseditor;
    private boolean linePaint = true;
    private String address;
    private TextView selectPaintTV;
    private TextView paintNameAddTV;

    private TextView paintNameAddTV1;
    private TextView paintNameTV1;
    private TextView lineTypeTV1;

    private void initView() {
        addressShare = getSharedPreferences("information_addresspiant", Context.MODE_PRIVATE);
        addresseditor = addressShare.edit();
        linePaint = addressShare.getBoolean("linePaint", true);
        address = addressShare.getString("address", "");
        paintName = addressShare.getString("paintName", "");

        address1 = addressShare.getString("address1", "");
        paintName1 = addressShare.getString("paintName1", "");
        linePaintIV = (ImageView) findViewById(R.id.linePaintIV);
        paintNameTV = (TextView) findViewById(R.id.paintNameTV);
        lineTypeTV = (TextView) findViewById(R.id.lineTypeTV);
        selectPaintTV = (TextView) findViewById(R.id.selectPaintTV);
        paintNameAddTV = (TextView) findViewById(R.id.paintNameAddTV);
        lineTypeTV1 = (TextView) findViewById(R.id.lineTypeTV1);

        paintNameAddTV1 = (TextView) findViewById(R.id.paintNameAddTV1);
        paintNameTV1 = (TextView) findViewById(R.id.paintNameTV1);
        mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        mXt4131 = (RadioButton) findViewById(R.id.xt4131);
        mXt432 = (RadioButton) findViewById(R.id.xt432);
        int printer = addressShare.getInt("printer", -1);
        if (printer != -1) {
            mRadioGroup.check(printer);
        }
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                RadioButton rb = (RadioButton) findViewById(group.getCheckedRadioButtonId());

                addresseditor.putInt("printer",group.getCheckedRadioButtonId());
                addresseditor.putString("printername", rb.getText().toString());
                addresseditor.commit();
            }
        });

        if (linePaint) {
            linePaintIV.setBackgroundResource(R.drawable.on_paint);
        } else {
            linePaintIV.setBackgroundResource(R.drawable.off_paint);
        }

        if (!StringUtil.isEmpty(address)) {
            paintNameAddTV.setText(paintName);
            paintNameTV.setText(address);
            lineTypeTV.setText("已连接");
        } else {
            paintNameAddTV.setText(paintName);
            paintNameTV.setText("无设备");
            lineTypeTV.setText("未连接");
        }
        if (!StringUtil.isEmpty(address1)) {
            paintNameAddTV1.setText(paintName1);
            paintNameTV1.setText(address1);
            lineTypeTV1.setText("已连接");
        } else {
            paintNameAddTV1.setText(paintName1);
            paintNameTV1.setText("无设备");
            lineTypeTV1.setText("未连接");
        }


        linePaintIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linePaint = addressShare.getBoolean("linePaint", true);
                if (linePaint) {
                    addresseditor.putBoolean("linePaint", false);
                    addresseditor.commit();
                    linePaintIV.setBackgroundResource(R.drawable.off_paint);
                } else {
                    addresseditor.putBoolean("linePaint", true);
                    addresseditor.commit();
                    linePaintIV.setBackgroundResource(R.drawable.on_paint);
                }
            }
        });
        selectPaintTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                selectPaint();
                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


    }

    @Override
    protected String settiltile() {
        return "打印机设置";
    }

    @Override
    protected int getLayoutRsid() {
        return R.layout.activity_set_paint;
    }

    /**
     * BluetoothAdapter开始发现设备
     */




    private final int REQUEST_PERMISSION_BT = 100;

    @Override
    protected void onResume() {
        super.onResume();
        fillAdapter();
        String mTitle = "已配对的蓝牙设备  数量:" + mPrinterDevices.size();
        mUPaireTitle.setText(mTitle);
        checkPermission();

    }

    private void fillAdapter() {
        //推荐使用 BluetoothUtil.getPairedPrinterDevices()
        mPrinterDevices = BluetoothUtil.getPairedDevices();
        mAdapter.clear();
        mAdapter.addAll(mPrinterDevices);
        refreshButtonText(mPrinterDevices);
    }

    private void refreshButtonText(List<BluetoothDevice> printerDevices) {

        boolean isaddress  = false;//默认不存在.
        boolean isaddress1  = false;//默认不存在.


        if (printerDevices.size() > 0) {
            selectPaintTV.setText("配对更多设备");
        } else {
            selectPaintTV.setText("还未配对打印机，去设置");
        }

        for (int i = 0; i < printerDevices.size(); i++) {
            if (address.equals(printerDevices.get(i).getAddress())) {
                isaddress = true;
            }
        }
        if (isaddress) {

        }else {
            addresseditor.putString("address", "");
            addresseditor.putString("paintName","");
            addresseditor.commit();
            paintNameAddTV.setText("-----------------");
            paintNameTV.setText("-----------------");
            lineTypeTV.setText("未连接");

        }


        for (int i = 0; i < printerDevices.size(); i++) {
            if (address1.equals(printerDevices.get(i).getAddress())) {
                isaddress1 = true;
            }
        }
        if (isaddress1) {

        }else {
            addresseditor.putString("address1", "");
            addresseditor.putString("paintName1","");
            addresseditor.commit();
            paintNameAddTV1.setText("-----------------");
            paintNameTV1.setText("-----------------");
            lineTypeTV1.setText("未连接");

        }

     /*   paintNameAddTV.setText(addressShare.getString("paintName","-----------------"));
        paintNameTV.setText(addressShare.getString("address","-----------------"));
        if (addressShare.getString("address", "") != "") {
            lineTypeTV.setText("已连接");
        }else {
            lineTypeTV.setText("未连接");
        }

        paintNameAddTV1.setText(addressShare.getString("paintName1","-----------------"));
        paintNameTV1.setText(addressShare.getString("address1","-----------------"));
        if (addressShare.getString("address1", "") != "") {
            lineTypeTV1.setText("已连接");
        }else {
            lineTypeTV1.setText("未连接");
        }  */

    }

    /* String str = "";
        boolean is  = false;//默认不存在.
        List<String> all  = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            if (str.equals(all.get(i))){
                //存在
                is = true;
            }
        }
        if (is){
            //存在
        }*/


    // onResume 中进行调用
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                //TODO 提示权限已经被禁用 且不在提示
                return;
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSION_BT);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERMISSION_BT:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //TODO 请求权限成功
                } else {
                    //TODO 提示权限已经被禁用
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private String type;
    private List<SetPaintBean> beanList = new ArrayList<>();




    /*蓝牙适配器*/
    class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {

        public DeviceListAdapter(Context context) {
            super(context, 0);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final BluetoothDevice device = getItem(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_bluetooth_device, parent, false);
            }

            TextView tvDeviceName = (TextView) convertView.findViewById(R.id.tv_device_name);
//            CheckBox cbDevice = (CheckBox) convertView.findViewById(R.id.cb_device);
            TextView viewById = (TextView) convertView.findViewById(R.id.address);
            Button biaoqian = (Button) convertView.findViewById(R.id.biaoqian);
            Button xiaopiao = (Button) convertView.findViewById(R.id.xiaopiao);
            tvDeviceName.setText(device.getName());
            viewById.setText(device.getAddress());
//            cbDevice.setChecked(position == mSelectedPosition);
            xiaopiao.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    addresseditor.putString("address1", device.getAddress());
                    addresseditor.putString("paintName1", device.getName());
                    addresseditor.commit();
                    paintNameAddTV1.setText(device.getName());
                    paintNameTV1.setText(device.getAddress());
                    lineTypeTV1.setText("已连接");
                    Toast.makeText(getContext(), "设置小票成功", Toast.LENGTH_SHORT).show();
                }
            });
            biaoqian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    addresseditor.putString("address", device.getAddress());
                    addresseditor.putString("paintName", device.getName());
                    addresseditor.commit();
                    paintNameAddTV.setText(device.getName());
                    paintNameTV.setText(device.getAddress());
                    lineTypeTV.setText("已连接");
                    Toast.makeText(getContext(), "设置标签成功", Toast.LENGTH_SHORT).show();                }
            });
            return convertView;
        }
    }

}
